"""响应序列化器和混入类"""
from rest_framework import serializers
from rest_framework.response import Response
from django.utils import timezone

def create_success_response_serializer(data_serializer, default_message="操作成功", suffix=""):
    """创建成功响应序列化器的辅助函数

    Args:
        data_serializer: 数据序列化器类或已实例化的序列化器(如many=True)
        default_message: 默认响应消息
        suffix: 序列化器名称后缀，用于区分不同的响应类型
    """
    class SuccessResponseSerializer(serializers.Serializer):
        code = serializers.IntegerField(default=200, help_text="状态码")
        message = serializers.CharField(default=default_message, help_text="响应消息")
        # 🔑 关键：支持传入序列化器类或已实例化的序列化器(如many=True)
        # 检查是否是已实例化的序列化器（包括ListSerializer）
        if hasattr(data_serializer, 'child'):
            # 已实例化的序列化器，直接使用
            data = data_serializer
        else:
            # 序列化器类，需要实例化
            data = data_serializer(help_text="响应数据")
        timestamp = serializers.DateTimeField(help_text="响应时间戳")

        class Meta:
            # 🔑 关键：获取序列化器类名，处理已实例化的情况
            ref_name = f"{data_serializer.__name__}SuccessResponse{suffix}"

    return SuccessResponseSerializer


class ErrorResponseSerializer(serializers.Serializer):
    """错误响应序列化器"""
    code = serializers.IntegerField(help_text="错误状态码")
    message = serializers.CharField(help_text="错误消息")
    errors = serializers.DictField(required=False, help_text="详细错误信息")
    timestamp = serializers.DateTimeField(help_text="响应时间戳")

class ValidationErrorResponseSerializer(ErrorResponseSerializer):
    """验证错误响应序列化器"""
    pass

class UnauthorizedErrorResponseSerializer(ErrorResponseSerializer):
    """未授权错误响应序列化器"""
    pass

class ForbiddenErrorResponseSerializer(ErrorResponseSerializer):
    """权限不足错误响应序列化器"""
    pass

class NotFoundErrorResponseSerializer(ErrorResponseSerializer):
    """资源不存在错误响应序列化器"""
    pass

class ConflictErrorResponseSerializer(ErrorResponseSerializer):
    """冲突错误响应序列化器"""
    pass

class ApiResponseMixin:
    """统一API响应格式混入类 - 用于自定义Action"""

    def success_response(self, data=None, message="操作成功", code=200):
        """返回成功响应"""
        response_data = {
            'code': code,
            'message': message,
            'data': data,
            'timestamp': timezone.now().isoformat()
        }
        return Response(response_data, status=code)

    def error_response(self, message="操作失败", errors=None, code=400):
        """返回错误响应"""
        response_data = {
            'code': code,
            'message': message,
            'timestamp': timezone.now().isoformat()
        }
        if errors:
            response_data['errors'] = errors
        return Response(response_data, status=code)
